package com.wcs.exam.common.util;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 队列属性复制
 *
 * @author wcs
 */
@Slf4j
public final class BeanUtil {

    private BeanUtil() {
    }

    /**
     * @param source
     * @param clazz
     */
    public static <T> T copyProperties(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        T t = null;
        try {
            t = clazz.getDeclaredConstructor().newInstance();
            cn.hutool.core.bean.BeanUtil.copyProperties(source, t);
        } catch (Exception e) {
            log.error("异常", e);
        }
        return t;
    }

    /**
     * @param source
     * @param clazz
     */
    public static <T> List<T> copyProperties(List<?> source, Class<T> clazz) {
        if (source.isEmpty()) {
            return Collections.emptyList();
        }
        List<T> res = new ArrayList<>(source.size());
        for (Object o : source) {
            res.add(copyProperties(o, clazz));
        }
        return res;
    }

    public static <T> T mapToBean(Map<?, ?> source, Class<T> clazz) {
        return cn.hutool.core.bean.BeanUtil.toBeanIgnoreCase(source, clazz, true);
    }

    public static <T> List<T> mapToBean(List<Map> source, Class<T> clazz) {
        if (source.isEmpty()) {
            return Collections.emptyList();
        }
        List<T> res = new ArrayList<>(source.size());
        for (Map o : source) {
            res.add(mapToBean(o, clazz));
        }
        return res;
    }

    /**
     * 把对象转换为实体
     *
     * @param source 对象
     * @param clazz  实体类型
     * @return 实体对象
     */
    public static <T> T objToBean(Object source, Class<T> clazz) {
        return cn.hutool.core.bean.BeanUtil.toBeanIgnoreError(source, clazz);
    }
}
